<template>
  <BasicModal
    width="1200px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    okText="保存"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <Row :gutter="24">
      <Col :span="8">
        <Card style="min-height: 400px; overflow: scroll">
          <MenuTree v-if="permissionId" :permission-id="permissionId" @select="handleSelect" />
        </Card>
      </Col>
      <Col :span="16">
        <Table
          :scroll="{ y: 400 }"
          :row-selection="{ selectedRowKeys: apiSelectedRowKeys, onChange: onSelectChange }"
          :columns="apiColumns"
          :data-source="apiList"
          :pagination="false"
          :row-key="'id'"
          bordered
        >
          <template #bodyCell="{ column, text, index }">
            <template v-if="column.dataIndex === 'serialNumber'">
              <div>
                <span> {{ index + 1 }}</span>
              </div>
            </template>
            <template
              v-else-if="['permissionName', 'permissionCode', 'sort'].includes(column.dataIndex)"
            >
              <div>
                {{ text }}
              </div>
            </template>
          </template>
        </Table>
      </Col>
    </Row>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Card, Col, Empty, Row, Table } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    bindPermissionApiRelation,
    queryApiCheckedListByMenuIdOfPermissionId,
  } from '/@/api/system/system';
  import MenuTree from '/@/views/system/permission/MenuTree.vue';
  import { ApiResp } from '/@/api/system/modal/apiModel';
  import { PermissionApiReq } from '/@/api/system/modal/permissionApiModel';
  import { apiColumns } from '/@/views/system/permission/permission.data';

  export default defineComponent({
    name: 'PermissionMenuApiModal',
    components: {
      Table,
      Card,
      Row,
      Col,
      MenuTree,
      BasicModal,
    },
    emits: ['success', 'register', 'cancel'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const id = ref('');
      const checkedMenuId = ref('');
      const loading = ref(false);

      const apiSelectedRowKeys = ref<string[]>([]);
      const apiList = ref<ApiResp[]>([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        id.value = data?.record?.id;
      });

      const getTitle = computed(() => '授权菜单');

      const onSelectChange = (selectedRowKeys: string[]) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        apiSelectedRowKeys.value = selectedRowKeys;
      };

      watch(
        () => id,
        () => {
          apiSelectedRowKeys.value = [];
          apiList.value = [];
        },
        { deep: true },
      );

      async function handleSelect(menuId = '') {
        if (menuId) {
          checkedMenuId.value = menuId;
          const permissionApiReq: PermissionApiReq = {
            permissionId: unref(id),
            menuId: menuId,
          };
          apiList.value = await queryApiCheckedListByMenuIdOfPermissionId(permissionApiReq);
          apiSelectedRowKeys.value = [];
          if (apiList.value && apiList.value.length > 0) {
            for (const apiResp of apiList.value) {
              if (apiResp.checked && apiResp.id) {
                apiSelectedRowKeys.value.push(apiResp.id);
              }
            }
          }
        }
      }

      async function handleSubmit() {
        try {
          if (!unref(checkedMenuId)) {
            createMessage.warn('请点击选择菜单');
            return;
          }
          const permissionApiReq: PermissionApiReq = {
            permissionId: unref(id),
            menuId: unref(checkedMenuId),
            apiIds: unref(apiSelectedRowKeys),
          };
          await bindPermissionApiRelation(permissionApiReq);
          // closeModal();
          createMessage.success('保存成功');
          emit('success', {
            isUpdate: unref(isUpdate),
            values: { menuIds: unref(apiSelectedRowKeys), id: unref(id) },
          });
        } catch (error: any) {
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          if (msg) {
            createMessage.error(msg);
          }
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function handleCancel() {
        emit('cancel');
      }

      return {
        apiColumns,
        simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
        permissionId: id,
        registerModal,
        getTitle,
        loading,
        apiSelectedRowKeys,
        apiList,
        onSelectChange,
        handleSelect,
        handleSubmit,
        handleCancel,
      };
    },
  });
</script>
<style lang="less" scoped>
  ::-webkit-scrollbar {
    width: 3px;
    height: 0px;
  }

  ::-webkit-scrollbar-track-piece {
    background-color: rgba(0, 0, 0, 0.2);
    -webkit-border-radius: 6px;
  }

  ::-webkit-scrollbar-thumb:vertical {
    height: 3px;
    background-color: rgba(125, 125, 125, 0.7);
    -webkit-border-radius: 6px;
  }

  ::-webkit-scrollbar-thumb:horizontal {
    width: 3px;
    background-color: rgba(125, 125, 125, 0.7);
    -webkit-border-radius: 6px;
  }
</style>
